package com.stylefeng.guns.modular.system.task;

import java.text.ParseException;
import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.stylefeng.guns.core.util.WebClientUtil;
import com.stylefeng.guns.modular.system.constants.ImportContants;
import com.stylefeng.guns.modular.system.model.Mkdata;
import com.stylefeng.guns.modular.system.service.IMkdataService;

@Service
public class MkDataImportTask {
	
	private Logger log = LoggerFactory.getLogger(MkDataImportTask.class);
	
	@Autowired
	private IMkdataService mkdataService;
	
	public void execute(boolean isHoliday) {
		if(isHoliday){
			try{
				Document document =  WebClientUtil.getHtmlPage(ImportContants.getFormatDayMacdPathStr(), 5000);
				if(document != null){
					parseData(1,document);//macd
				}
				document =  WebClientUtil.getHtmlPage(ImportContants.getFormatDayKdjPathStr(), 5000);
				if(document != null){
					parseData(2,document);//kdj
				}
				document =  WebClientUtil.getHtmlPage(ImportContants.getFormatDayMacdKdjPathStr(), 5000);
				if(document != null){
					parseData(3,document);//kdj
				}
			}catch(Exception e){
				log.error("解析数据错误!" ,e);
			}
		}
	}
	
	private void parseData(int type, Document doc) throws ParseException{
		Elements elements =  doc.select("tbody").select("tr");
		for(Element tdelement: elements){
			Elements tdes = tdelement.select("td");
			if(StringUtils.isNotEmpty(tdes.get(0).text()) ||
					StringUtils.isNotEmpty(tdes.get(0).text())){
				Date date = assembleDate(tdes.get(0).text());
				String dm = tdes.get(1).text();
				
				Mkdata mkdata = new Mkdata();
				mkdata.setgDate(date);
				mkdata.setgDm(dm);
				mkdata.setgMkType(type);
				mkdata = mkdataService.selectByMkData(mkdata);
				if(mkdata == null){
					mkdata = new Mkdata();
					mkdata.setgDate(date);
					mkdata.setgDm(dm);
					mkdata.setgMkType(type);
					mkdataService.insert(mkdata);
				}
			}
		}
	}
	
	private Date assembleDate(String str) throws ParseException{
		String datas[] = StringUtils.split(str,"__");
		StringBuffer buffer = new StringBuffer();
		buffer.append(datas[0]).append("-")
		.append(datas[1]).append("-")
		.append(datas[2]).append(" ")
		.append(datas[3]).append(":")
		.append("00");
		return DateUtils.parseDate(buffer.toString(), "yyyy-MM-dd HH:mm:ss");
	}
}
